package com.coolrui.config;

import com.coolrui.common.system.ApiResult;
import com.coolrui.common.enums.ResultCodeEnum;
import com.coolrui.common.system.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    //进行具体异常分类处理
    @ExceptionHandler(Exception.class)
    public ApiResult exceptionHandle(Exception exception) {
        Map<String, String> validMap = new HashMap<>();
        //判断异常类型
        if (exception instanceof BindException) {
            //拦截的是validator绑定的异常
            BindException bindException = (BindException) exception;
            List<FieldError> fieldErrors = bindException.getBindingResult().getFieldErrors();

            for (FieldError fieldError : fieldErrors) {
                // FieldError 获取到错误提示
                String message = fieldError.getDefaultMessage();
                // 获取错误的属性的名字
                String field = fieldError.getField();
                validMap.put(field,message);
            }
            return Response.makeErrRsp(ResultCodeEnum.VALID, ResultCodeEnum.VALID.getMessage(), validMap);
        }

        //未处理类型，返回系统异常
        return Response.makeErrRsp(ResultCodeEnum.EXCEPTION, exception.getMessage());
    }
}

